using System.Collections.Generic;
using System.Linq;
using LitJson;
using UnityEngine;
using UnityEngine.UI;
namespace CGF
{
    public partial class PanelWithdrawAdd : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private string currSelectMethod;
        private JsonData myMethods;
        private CButton[] dropdownCellPrefabs;
        private List<string> bankCodes = new List<string>();
        private string currPixType;
        private string pixInputContent = "";

        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelWithdrawAdd>(UILayer.Normal, RootComponent.instance, true);
        }

        public static void Close()
        {
            RootComponent.instance.GetComponent<PanelWithdraw>().ReqData();
            UIManagerComponent.instance.CloseUI<PanelWithdrawAdd>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelWithdrawAdd", layer, isFloat);
            BindProperties(transform);

            BtnClose.SetClick(Close);

            MethodDropdown.rectTransform.anchoredPosition = new Vector2(0, MethodDropdown.rectTransform.anchoredPosition.y);
            dropdownCellPrefabs = new CButton[MethodDropdown.cells.Length];
            for (int i = 0; i < dropdownCellPrefabs.Length; i++)
            {
                dropdownCellPrefabs[i] = MethodDropdown.cells[i];
                dropdownCellPrefabs[i].gameObject.SetActive(false);
            }
            MethodDropdown.ResetCells(new CButton[0]);
            BtnMethod.SetClick(() =>
            {
                MethodDropdown.Show();
            });
            MethodDropdown.SetOnSelect(index =>
            {
                var image = BtnMethod.gameObject.Get<Image>("Icon");
                image.sprite = MethodDropdown.cells[index].gameObject.Get<Image>("Icon").sprite;
                image.SetNativeSize();
                string method = MethodDropdown.cells[index].gameObject.Get<Text>("Text").text;
                BtnMethod.gameObject.Get<Text>("Name").text = method;
                currSelectMethod = method.ToLower();
            });

            VNBankDropdown.rectTransform.anchoredPosition = new Vector2(0, VNBankDropdown.rectTransform.anchoredPosition.y);
            VNBankDropdown.SetCellUpdateCallback((RectTransform cell, int index) =>
            {
                cell.gameObject.Get<Text>("Text").text = bankCodes[index];
                cell.GetComponent<CButton>().SetClick(() =>
                {
                    BtnBankCode.gameObject.Get<Text>("Name").text = bankCodes[index];
                    VNBankDropdown.GetComponent<Dropdown>().Hide();
                });
            });
            bankCodes = new List<string>(Config.BankCodes[CGFConfig.Instance.ReleaseArea].Keys);
            bankCodes.Sort();
            if (bankCodes.Count > 0)
            {
                BtnBankCode.gameObject.Get<Text>("Name").text = bankCodes[0];
            }
            VNBankDropdown.SetTotalNumber(bankCodes.Count);

            BtnBankCode.SetClick(() =>
            {
                VNBankDropdown.GetComponent<Dropdown>().Show();
            });

            BtnPixSelect.SetClick(() =>
            {
                PixDropdown.Show();
            });

            InputPIXAccount.characterLimit = 14;
            BtnPixSelect.text.text = PixDropdown.cells[0].text.text;
            currPixType = BtnPixSelect.text.text;
            PixDropdown.SetOnSelect(index =>
            {
                BtnPixSelect.text.text = PixDropdown.cells[index].text.text;
                if (currPixType != BtnPixSelect.text.text)
                {
                    currPixType = BtnPixSelect.text.text;
                    InputPIXAccount.text = "";
                }
                if (currPixType == "CPF")
                {
                    InputPIXAccount.characterLimit = 14;
                }
                else if (currPixType == "Email")
                {
                    InputPIXAccount.characterLimit = 35;
                }
                else if (currPixType == "Phone")
                {
                    InputPIXAccount.characterLimit = 11;
                }
            });

            InputPIXAccount.SetInputAction(input =>
            {
                if (currPixType == "CPF" && pixInputContent.Length < input.Length)
                {
                    if (InputPIXAccount.text.Length == 3 || InputPIXAccount.text.Length == 7)
                    {
                        InputPIXAccount.text += ".";
                        InputPIXAccount.MoveTextEnd(false);
                    }
                    else if (InputPIXAccount.text.Length == 11)
                    {
                        InputPIXAccount.text += "-";
                        InputPIXAccount.MoveTextEnd(false);
                    }
                }
                pixInputContent = input;
            }, false);

            BtnAdd.SetClick(async () =>
            {

                JsonData data = new JsonData();
                data["method"] = currSelectMethod.Contains("usdt") ? "usdt" : currSelectMethod;
                switch (data["method"].ToString())
                {
                    case "pix":
                        if (BtnPixSelect.text.text == "CPF")
                        {
                            if (!StringHelper.IsPIX(InputPIXAccount.text))
                            {
                                CGF.Dialog.Alert(CommAssets.instance.I18N_invalid_cformat);
                                return;
                            }
                        }
                        else if (BtnPixSelect.text.text == "Email")
                        {
                            if (!StringHelper.IsEmail(InputPIXAccount.text))
                            {
                                CGF.Dialog.Alert(CommAssets.instance.I18N_invalid_cformat);
                                return;
                            }
                        }
                        else if (BtnPixSelect.text.text == "Phone")
                        {
                            InputPIXAccount.text = InputPIXAccount.text.Replace("+55", "");
                            if (InputPIXAccount.text.StartsWith("55"))
                            {
                                InputPIXAccount.text = InputPIXAccount.text.Substring(2);
                            }
                            if (!StringHelper.IsPhoneNum(InputPIXAccount.text))
                            {
                                CGF.Dialog.Alert(CommAssets.instance.I18N_invalid_cformat);
                                return;
                            }
                        }
                        data["account"] = InputPIXAccount.text;
                        data["bank_code"] = BtnPixSelect.text.text;
                        break;
                    case "usdt":
                        if (string.IsNullOrEmpty(InputAccount.text))
                        {
                            CGF.Dialog.Alert(I18N_please_input_account);
                            return;
                        }
                        if (InputAccount.text.Contains(" "))
                        {
                            CGF.Dialog.Alert(CommAssets.instance.I18N_account_canot_space);
                            return;
                        }
                        data["account"] = InputAccount.text;
                        break;
                    case "bank":
                        if (string.IsNullOrEmpty(InputName.text))
                        {
                            CGF.Dialog.Alert(I18N_please_input_name);
                            return;
                        }
                        if (string.IsNullOrEmpty(InputAccount.text))
                        {
                            CGF.Dialog.Alert(I18N_please_input_account);
                            return;
                        }
                        if (InputAccount.text.Contains(" "))
                        {
                            CGF.Dialog.Alert(CommAssets.instance.I18N_account_canot_space);
                            return;
                        }
                        data["bank_code"] = Config.BankCodes[CGFConfig.Instance.ReleaseArea][BtnBankCode.gameObject.Get<Text>("Name").text];
                        data["bank_owner"] = InputName.text;
                        data["account"] = InputAccount.text;
                        break;
                }
                var res = await Network.Post("/v1/withdrawal/way", data);
                if (res.success)
                {
                    RootComponent.instance.GetComponent<PanelWithdraw>().ShowWays();
                    Close();
                    CGF.Dialog.Alert(I18N_add_success);
                }
            });
            ScaleIn(Dialog.transform);
            ReqData();
        }

        private async void ReqData()
        {
            var res = await Network.Get("/v1/withdrawal/way");
            myMethods = res.jsonData["data"];
            for (int i = 0; i < myMethods.Count; i++)
            {
                if (myMethods[i]["method"].ToString().Contains("usdt"))
                {
                    myMethods[i]["method"] = "usdt";
                }
            }
            if (!BtnAdd) return;

            for (int i = 0; i < MethodDropdown.cells.Length; i++)
            {
                GameObject.Destroy(MethodDropdown.cells[i].gameObject);
            }
            List<CButton> myCells = new List<CButton>();
            for (int i = 0; i < dropdownCellPrefabs.Length; i++)
            {
                CButton prefab = null;
                if (i == 0 && CurrCountryHave("pix") && !IHaveAddedMethod("pix"))
                {
                    prefab = dropdownCellPrefabs[0];
                }
                else if (i == 1 && CurrCountryHave("usdt") && !IHaveAddedMethod("usdt"))
                {
                    prefab = dropdownCellPrefabs[1];
                }
                else if (i == 2 && CurrCountryHave("bank") && !IHaveAddedMethod("bank"))
                {
                    prefab = dropdownCellPrefabs[2];
                }
                if (prefab)
                {
                    CButton cell = GameObject.Instantiate(prefab, MethodDropdown.transform, false);
                    cell.gameObject.SetActive(true);
                    myCells.Add(cell);
                }
            }
            MethodDropdown.ResetCells(myCells.ToArray());
            if (myCells.Count > 0)
            {
                MethodDropdown.InvokeSelect(0);
                OnSelectMethod(MethodDropdown.GetText(0).ToLower());
            }
        }

        private bool IHaveAddedMethod(string method)
        {
            for (int i = 0; i < myMethods.Count; i++)
            {
                if (myMethods[i]["method"].ToString().Contains(method))
                {
                    return true;
                }
            }
            return false;
        }

        private bool CurrCountryHave(string method)
        {
            for (int i = 0; i < PanelWithdraw.CanUseMethods[CGFConfig.Instance.ReleaseArea].Length; i++)
            {
                if (PanelWithdraw.CanUseMethods[CGFConfig.Instance.ReleaseArea][i] == method)
                {
                    return true;
                }
            }
            return false;
        }

        private void OnSelectMethod(string method)
        {
            switch (method)
            {
                case "pix":
                    BtnBankCode.gameObject.SetActive(false);
                    InputName.gameObject.SetActive(false);
                    InputAccount.gameObject.SetActive(false);
                    InputPIX.gameObject.SetActive(true);
                    break;
                case "usdt":
                    BtnBankCode.gameObject.SetActive(false);
                    InputName.gameObject.SetActive(false);
                    InputAccount.gameObject.SetActive(true);
                    InputPIX.gameObject.SetActive(false);
                    break;
                case "bank":
                    BtnBankCode.gameObject.SetActive(true);
                    InputName.gameObject.SetActive(true);
                    InputAccount.gameObject.SetActive(true);
                    InputPIX.gameObject.SetActive(false);
                    break;
            }
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
